#include <mw/eikappui.h>
#include <mw/APGWGNAM.H> //CApaWindowGroupName

#include "CGainFocusEventObserver.h"

CGainFocusEventObserver* CGainFocusEventObserver::NewL(MFocusEventObserver& aObserver,
                                                       TInt aWgroup)
	{
	CGainFocusEventObserver* self = new (ELeave) CGainFocusEventObserver(aObserver);
    CleanupStack::PushL( self );
    self->ConstructL(aWgroup);
    CleanupStack::Pop( self );
	return self;
	}

void CGainFocusEventObserver::ConstructL(TInt aWgroup)
	{
	CCoeEnv::Static()->RootWin().EnableFocusChangeEvents();
	iSession = new (ELeave)RWsSession();
	User::LeaveIfError(iSession->Connect());

    TUint groupHandle = iSession->GetWindowGroupHandle(aWgroup);
    iWGroup = new(ELeave) RWindowGroup(*iSession);
    iWGroup->Construct(groupHandle); //connect to aWgroup group
    User::LeaveIfError(iWGroup->EnableFocusChangeEvents());

    CActiveScheduler::Add(this);
	startListening();
	}

CGainFocusEventObserver::CGainFocusEventObserver(MFocusEventObserver& aObserver):
		CActive(EPriorityStandard),
		iObserver(&aObserver)
	{
	}

CGainFocusEventObserver::~CGainFocusEventObserver()
	{
    iWGroup->Close();
	iSession->Close();
	delete iSession;
    delete iWGroup;
	}

void CGainFocusEventObserver::RunL()
	{
	if (iStatus == KErrNone)
		{
		TWsEvent event;
		iSession->GetEvent(event);
		iObserver->Notify(event.Type());
		}

	if (iStatus != KErrCancel)
		{
		startListening();
		}
	}

void CGainFocusEventObserver::DoCancel()
	{
	iSession->EventReadyCancel();
	}

void CGainFocusEventObserver::startListening()
	{
	iSession->EventReady(&iStatus);
	SetActive();
	}
